﻿/*
 * 编辑器组件
 */
if (typeof (editorAlign) =='undefined') { //自定义对齐方式
    let editorAlign = Quill.import('attributors/style/align');
    editorAlign.whitelist = ['right', 'center', 'justify'];
    Quill.register(editorAlign, true);
}
if (typeof (editorFont) == 'undefined') { //自定义字体
    let editorFont = Quill.import('formats/font');
    editorFont.whitelist = ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial', 'sans-serif'];
    Quill.register(editorFont, true);
}
Vue.use(VueQuillEditor)

Vue.component('dt-editor', {
    template: '<quill-editor :value="content" :options="options" @input="input" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @change="onEditorChange($event)" ></quill-editor>',
    props: {
        mini: {
            type: Boolean,
            default: false,
        },
        value: String,
        placeholder: String
    },
    data: function () {
        return {
            isload: false,
            content: '',
            options: {
                placeholder: this.placeholder,
                theme: 'snow',
                modules: {
                    imageResize: {
                        displayStyles: {
                            backgroundColor: 'black',
                            border: 'none',
                            color: 'white'
                        },
                        modules: ['Resize', 'DisplaySize', 'Toolbar']
                    },
                    toolbar: {
                        container: [],
                        handlers: {
                            'image': function () {
                                var self = this;
                                var fileInput = this.container.querySelector('input.ql-image[type=file]');
                                if (fileInput === null) {
                                    fileInput = document.createElement('input');
                                    fileInput.setAttribute('type', 'file');
                                    fileInput.setAttribute('accept', 'image/*');
                                    fileInput.classList.add('ql-image');
                                    // 监听选择文件
                                    fileInput.addEventListener('change', async () => {
                                        const formData = new FormData();
                                        formData.append('file', fileInput.files[0])
                                        //开始上传
                                        AxiosAjax({
                                            url: '/upload',
                                            method: 'file',
                                            data: formData,
                                            loading: true,
                                            success: function (res) {
                                                let length = self.quill.getSelection(true).index;
                                                let imgUrl = baseApi + res.data[0].filePath;
                                                self.quill.insertEmbed(length, 'image', imgUrl);
                                                self.quill.setSelection(length + 1);
                                            }
                                        });
                                        fileInput.value = ''
                                    })
                                    this.container.appendChild(fileInput);
                                }
                                fileInput.click();
                            }
                        }
                    }
                }
            }
        }
    },
    methods: {
        input(val) {
            //替换图片成相对路径
            let newContent = val.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                if (capture.indexOf(baseApi) != -1) {
                    return match.replace(baseApi, '');
                }
                return match;
            });
            //通知更新
            this.$emit('input', newContent);
        },
        //失去焦点事件
        onEditorBlur(e) {
            this.$emit('blur', e)
        },
        //获取焦点事件
        onEditorFocus(e) {
            this.$emit('focus', e)
        },
        //change事件
        onEditorChange(e) {
            this.$emit('change', e)
        },

    },
    created: function () {
        //迷你样式
        const editorOptionMini = [
            [{ 'font': ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial', 'sans-serif'] }],     //字体
            [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],     //几级标题
            ['bold', 'italic', 'underline', 'strike'],    //加粗，斜体，下划线，删除线
            [{ 'color': [] }, { 'background': [] }],     // 字体颜色，字体背景颜色
            [{ 'align': [] }],    //对齐方式
            ['image', 'video'],    //上传图片、上传视频
            ['clean']    //清除字体样式
        ];
        //全部工具
        const editorOption = [
            [{ 'font': ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial', 'sans-serif'] }],,     //字体
            [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],     //几级标题
            ['bold', 'italic', 'underline', 'strike'],    //加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'],     //引用，代码块
            [{ 'header': 1 }, { 'header': 2 }],        // 标题，键值对的形式；1、2表示字体大小
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],     //列表
            [{ 'script': 'sub' }, { 'script': 'super' }],   // 上下标
            [{ 'indent': '-1' }, { 'indent': '+1' }],     // 缩进
            [{ 'direction': 'rtl' }],             // 文本方向
            [{ 'color': [] }, { 'background': [] }],     // 字体颜色，字体背景颜色
            [{ 'align': [] }],    //对齐方式
            ['image', 'video'],    //上传图片、上传视频
            ['clean'],    //清除字体样式
        ];
        this.options.modules.toolbar.container = this.mini ? editorOptionMini : editorOption;
    },
    mounted: function () {
        //把图片相对地址转换API地址
        if (this.value) {
            let newContent = this.value.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                if (capture.substring(0, 4).toLowerCase() != 'http') {
                    return match.replace(capture, baseApi + capture);
                }
                return match;
            });
            this.content = newContent;
        }
    },
    watch: {
        //把图片相对地址转换API地址
        value: function (newVal) {
            if (newVal && !this.isload) {
                let newContent = this.value.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                    if (capture.substring(0, 4).toLowerCase() != 'http') {
                        return match.replace(capture, baseApi + capture);
                    }
                    return match;
                });
                this.isload = true;
                this.content = newContent;
            }
        }
    }
});